package com.kk.quyan.utils.excelUtil;

import cn.hutool.http.HttpStatus;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.kk.quyan.entity.Material;
import com.kk.quyan.common.handler.CustomException;
import com.kk.quyan.service.MaterialService;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: Excel监听器
 * @author: Kk
 * @create: 2020-11-21 20:45
 **/
public class ExcelListener extends AnalysisEventListener<ExcelData> {
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    /**
     * 这个集合用于接收 读取Excel文件得到的数据
     */
    List<Material> list = new ArrayList<Material>();

    //构造器注入
    public MaterialService materialService;

    public ExcelListener(){}

    public ExcelListener(MaterialService materialService){
        this.materialService=materialService;
    }

    @Override
    public void invoke(ExcelData data, AnalysisContext analysisContext) {
        if (data==null){
            try {
                throw new CustomException(HttpStatus.HTTP_BAD_REQUEST,"文件数据未空");
            } catch (CustomException e) {
                e.printStackTrace();
            }
        }
        //System.out.println(data);
        Material material = new Material();
        material.setTitle(data.getTitle())
                .setType(data.getType())
                .setUrl(data.getUrl())
                .setDescription(data.getDescription());
        list.add(material);
        if (list.size()>=BATCH_COUNT){
            //每次处理五条数据
            saveMaterial();
            //清除
            list.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveMaterial();
        list.clear();
    }

    private void saveMaterial() {
        materialService.saveBatch(list);
        System.out.println(list);
    }
}
